<template>
  <div class="app-container">
    <div class="flex mb-4">
      <div class="md:w-1/3">
        <p class="text-xl mb-2">总计</p>
        <el-table :data="totalData" border stripe>
          <el-table-column v-for="col in columns"
                           :key="col.id"
                           :label="col.label"
                           :prop="col.property"
                           :width="col.width"
          >
          </el-table-column>
        </el-table>
      </div>
      <div class="flex-grow ml-8">
        <p class="text-xl mb-2">筛选</p>
        <div class="flex flex-wrap">
          <el-input
            v-model="listQuery.name"
            class="marginRB10"
            clearable
            placeholder="请输入公司名称"
            style="width: 200px"
          ></el-input>
          <el-input
            v-model="listQuery.id"
            class="marginRB10"
            clearable
            placeholder="请输入公司ID"
            style="width: 200px"
          ></el-input>
          <el-date-picker
            v-model="times"
            type="datetimerange"
            class="marginRB10"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="handleTimesChange">
          </el-date-picker>
          <el-select v-model.number="listQuery.status"
                      class="filter-item marginRB10"
                      filterable
                      placeholder="请选择状态"
                      style="width: 200px"
          >
            <el-option
              v-for="item in selectList"
              :key="item.key"
              :label="item.lab"
              :value="item.key"
            ></el-option>
          </el-select>
          <el-select v-model.number="listQuery.type"
                      class="filter-item marginRB10"
                      filterable
                      placeholder="请选择模式"
                      style="width: 200px"
          >
            <el-option
              v-for="item in modeList"
              :key="item.key"
              :label="item.lab"
              :value="item.key"
            ></el-option>
          </el-select>
          <el-button
            class="marginRB10"
            icon="el-icon-search"
            type="primary"
            @click="getList()"
          >搜索
          </el-button>
          <el-button class="marginRB10" @click="resetSubmit">重置</el-button>
        </div>
      </div>
    </div>
    <div class="flex items-center justify-between">
      <p class="text-xl">公司列表（{{ total }}）</p>
      <el-button
        class="filter-item marginRB10"
        icon="el-icon-plus"
        type="primary"
        @click="handleCreate()"
      >新增公司
      </el-button
      >
    </div>

    <el-table
      ref="dataList"
      :data="menuList"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
      row-key="id"
      style="margin-bottom: 20px"
    >
      <!-- <el-table-column :index="indexMethod" type="index" width="150" label="编号"></el-table-column> -->
      <el-table-column label="公司名称" prop="name"></el-table-column>
      <el-table-column label="公司ID" prop="id"></el-table-column>
      <el-table-column label="员工数" prop="user_total"></el-table-column>
      <el-table-column label="邀请人数（人）" prop="user_total" sortable width="150"></el-table-column>
      <el-table-column label="充值金额（元）" prop="recharge_total" sortable width="150"></el-table-column>
      <el-table-column label="创建时间" prop="created_at" sortable></el-table-column>
      <el-table-column label="状态" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 1" class="text-green-600">激活</span>
          <span v-if="scope.row.status === 0" class="text-red-500">已停用</span>
        </template>
      </el-table-column>
      <el-table-column label="模式" prop="type"></el-table-column>
      <el-table-column label="房间号" prop="room_code"></el-table-column>
      <el-table-column label="账号" prop="account"></el-table-column>
      <el-table-column label="操作" min-width="180">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="text"
            @click="handleCopy(scope.row)"
          >复制链接
          </el-button>
          <el-button v-if="scope.row.status === 1" type="text" size="default" @click="handleResetPassword(scope.row)" style="color: #f56c6c;">重置密码</el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="text"
            @click="handleChangeRoom(scope.row)"

          >更改房间
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleCheck(scope.row)"

          >查看
          </el-button>
          <el-button v-if="scope.row.status === 1" size="default" style="color: #f56c6c;" type="text"
                     @click="handleOutService(scope.row,0)"
          >停用
          </el-button>
          <!-- <el-button v-if="scope.row.status === 0" type="text" size="default" @click="handleOutService(scope.row,1)" style="color: #f56c6c;">开启</el-button> -->
          
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      v-show="total > 0"
      :limit.sync="listQuery.perPage"
      :page.sync="listQuery.page"
      :total="total"
      @pagination="getList"
    />

    <!-- 新增公司弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      center
      width="30%"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入公司名称"/>
        </el-form-item>
        <el-form-item label="模式" prop="type">
          <el-select v-model.number="form.type"
                      class="filter-item"
                      filterable
                      placeholder="请选择模式"
                      style="width: 200px"
          >
            <el-option
              v-for="item in modeList"
              :key="item.key"
              :label="item.lab"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="room_code">
          <el-input type="number" v-model="form.room_code" placeholder="请输入房间号"/>
        </el-form-item>
        <el-form-item label="管理员账号" prop="account">
          <el-input v-model="form.account" @keyup.native="form.account=check(form.account)" placeholder="请输入管理员账号"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" @keyup.native="form.password=check(form.password)" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="password_confirmation">
          <el-input v-model="form.password_confirmation" @keyup.native="form.password_confirmation=check(form.password_confirmation)" placeholder="再次输入密码"/>
        </el-form-item>
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入姓名"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <!-- 公司新增成功弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="successvisible"
      center
      width="30%"
      @close="closeDialog"
    >
      <div class="flex">
        <span class="w-24 text-right">后台链接：</span>
        <span>{{ successInfo.openLink }}</span>
      </div>
      <div class="flex">
        <span class="w-24 text-right">管理员账号：</span>
        <span>{{ successInfo.account }}</span>
      </div>
      <div class="flex">
        <span class="w-24 text-right">管理员密码：</span>
        <span>{{ successInfo.password }}</span>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="copyContent">复制</el-button>
        <el-button @click="successvisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- 公司停用弹窗 -->
    <el-dialog
      :title="stopUsingTitle"
      :visible.sync="outServiceVisible"
      center
      width="30%"
      @close="closeDialog"
    >
      <p v-if="isStopUsing === 0" class="mb-2 ml-4 text-yellow-500">停用后该公司渠道后台将无法登录</p>
      <p v-if="isStopUsing === 1" class="mb-2 ml-4 text-yellow-500">开启后该公司渠道后台将可以正常登录</p>
      <div class="flex mb-2">
        <span class="w-24 text-right">公司名称：</span>
        <span>{{ outServiceInfo.name }}</span>
      </div>
      <div class="flex">
        <span class="w-24 text-right">公司ID：</span>
        <span>{{ outServiceInfo.id }}</span>
      </div>
      <span slot="footer">
        <el-button v-if="isStopUsing === 0" type="danger" @click="outService">停用</el-button>
        <!-- <el-button v-if="isStopUsing === 1" type="primary" @click="outService">开启</el-button> -->
        <el-button @click="outServiceVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 重置密码 -->
    <el-dialog
      v-dialogDrag
      :visible.sync="resetVisible"
      center
      title="重置密码"
      width="30%"
      @close="handleDialogClose2"
    >
      <el-form
        ref="dataForm2"
        :model="resetform"
        :rules="resetPasswordRules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="resetform.account" placeholder="请输入管理员账号" disabled/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="resetform.password" placeholder="请输入密码"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="resetVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="onSubmitForm1()">
          确 认
        </el-button>
      </div>
    </el-dialog>

    <!-- 更改房间 -->
    <el-dialog
      v-dialogDrag
      :visible.sync="changeRoomVisible"
      center
      title="更改房间"
      width="30%"
      @close="handleDialogClose2"
    >
      <el-form
        ref="dataForm3"
        :model="changeRoomform"
        :rules="changeRoomRules"
        label-width="80px"
      >
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="changeRoomform.name" placeholder="公司名称" disabled/>
        </el-form-item>
        <el-form-item label="房间号" prop="room_code">
          <el-input type="number" v-model="changeRoomform.room_code" placeholder="请输入房间号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="changeRoomVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="onSubmitForm2()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listData, resetPassword, saveData, updateData, updateRoom } from '@/api/company'

export default {
  data() {
    return {
      times: [],
      changeRoomform: {
        name: '',
        room_code: ''
      },
      changeRoomRules: {
        room_code: [{ required: true, message: '请输入房间号', trigger: 'blur' }]
      },
      changeRoomVisible: false,
      resetform: {
        account: '',
        password: ''
      },
      resetPasswordRules: {
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      resetVisible: false,
      successInfo: {
        openLink: '',
        name: '',
        password: ''
      },
      adminPath: process.env.LOGIN_PATH + '?path=',
      isStopUsing: true,
      stopUsingTitle: '停用',
      outServiceInfo: {
        name: '',
        status: null,
        id: null
      },
      successvisible: false,
      dialogTitle: '',
      outServiceVisible: false,
      channel_user_link: '',
      register_link: '',
      totalData: [],
      columns: [
        {
          id: 1,
          label: '总邀请人数(人)',
          property: 'user_total',
          width: 'auto'
        },
        {
          id: 2,
          label: '总充值金额（元）',
          property: 'recharge_total',
          width: 'auto'
        }
      ],
      confirmBtn: false,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      selectList: [
        { key: 1, lab: '激活 ' },
        { key: 0, lab: '停用' }
      ],
      modeList: [
        { key: 'CPA', lab: 'CPA ' },
        { key: 'CPS', lab: 'CPS' }
      ],
      menuList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },
      form: {
        name: undefined
      },
      rules: {
        name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        account: [{ required: true, message: '请输入管理员账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        password_confirmation: [{ required: true, message: '请确认密码', trigger: 'blur' }],
        type: [{ required: true, message: '请选择模式', trigger: 'blur' }],
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        room_code: [{ required: true, message: '请输入房间号', trigger: 'blur' }]
      },
      confirmation: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    indexMethod(index) {
      return (this.listQuery.page - 1) * this.listQuery.perPage + index + 1
    },
    getList() {
      this.listLoading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
      }
      listData(this.listQuery).then(({ data }) => {
        this.menuList = data.list
        this.total = data.meta.total
        this.listLoading = false
        this.confirmBtn = false
        this.totalData = [data.header]
      })
    },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleOutService(row, status) {
      this.isStopUsing = status
      if (status === 1) {
        this.stopUsingTitle = '开启'
      } else {
        this.stopUsingTitle = '停用'
      }
      this.outServiceInfo.id = row.id
      this.outServiceInfo.name = row.name
      this.outServiceInfo.status = status
      this.outServiceVisible = true
    },
    handleChangeRoom(row) {
      this.changeRoomVisible = true
      this.changeRoomform.name = row.name
      this.changeRoomform.room_code = row.room_code
      this.changeRoomform.id = row.id
    },
    handleCheck(row) {
      this.$router.push({
        path: 'companyUser',
        query: {
          company_id: row.id
        }
      })
    },
    submitForm() {
      if (this.confirmBtn) return
      this.handleConfirmPassword()
      if (!this.confirmation) {
        return false
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid && this.dialogStatus === 'create') {
          this.confirmBtn = true
          let formData = new FormData()
          for (let item in this.form) {
            this.form[item] === undefined
              ? ''
              : formData.append(item, this.form[item])
          }
          saveData(formData).then((response) => {
            if (response.code === 200) {
              this.successvisible = true
              this.dialogTitle = '创建成功'
              this.successInfo.account = response.data.account
              this.successInfo.password = response.data.password
              this.successInfo.openLink = this.adminPath + response.data.login_path
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.confirmBtn = false
            }
          })
        }
      })
    },
    resetForm() {
      this.form = {
        name: undefined
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    },
    handleDialogClose2() {
      if (this.$refs['dataForm2']) {
        this.$refs['dataForm2'].clearValidate() // 清除整个表单的校验
      }
      if (this.$refs['dataForm3']) {
        this.$refs['dataForm3'].clearValidate() // 清除整个表单的校验
      }
      this.resetform = {
        account: '',
        password: ''
      }
    },
    resetSubmit() {
      this.listQuery = {
        page: 1,
        perPage: 10
      }
      this.times = []
      this.getList()
    },
    handleCopy(item) {
      this.copyContent2(item.login_path)
    },
    copyContent() {
      let link = '后台链接：' + this.successInfo.openLink + '；管理员账号：' + this.successInfo.account + '；管理员密码：' + this.successInfo.password
      let copyInput = document.createElement('input')
      document.body.appendChild(copyInput)
      copyInput.setAttribute('value', link)
      copyInput.select()
      document.execCommand('copy')
      this.$notify({
        type: 'success',
        message: '复制成功',
        position: 'top-right',
        showClose: false,
        duration: 3000
      })
      copyInput.remove()
      this.successvisible = false
    },
    copyContent2(login_path) {
      let link = this.adminPath + login_path
      let copyInput = document.createElement('input')
      document.body.appendChild(copyInput)
      copyInput.setAttribute('value', link)
      copyInput.select()
      document.execCommand('copy')
      this.$notify({
        type: 'success',
        message: '复制成功,请在地址栏打开链接',
        position: 'top-right',
        showClose: false,
        duration: 3000
      })
      copyInput.remove()
    },
    closeDialog() {
      this.successInfo = {
        openLink: '',
        account: '',
        password: ''
      }
    },
    outService() {
      updateData(this.outServiceInfo).then(res => {
        if (res.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
          this.outServiceVisible = false
        }
      })
    },
    handleResetPassword(row) {
      console.log(row)
      this.resetVisible = true
      this.resetform.account = row.account
    },
    setResetPassword(data) {
      resetPassword(data).then(res => {
        if(res.code === 200) {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.resetVisible = false
        }
      })
    },
    onSubmitForm1() {
      this.setResetPassword(this.resetform)
    },
    onSubmitForm2() {
      this.$refs['dataForm3'].validate((valid) => {
        if (valid) {
          this.setUpdateRoom({
            id: this.changeRoomform.id,
            room_code: this.changeRoomform.room_code
          })
        }
      })
    },
    handleConfirmPassword() {
      if(this.form.password != this.form.password_confirmation) {
        this.confirmation = false
        this.$message({
          type: 'warning',
          message: '请确认2次密码输入是否一样'
        })
      }else {
        this.confirmation = true
      }
    },
    handleTimesChange(val) {
      if(val) {
        this.listQuery.start_time = val[0]
        this.listQuery.end_time = val[1]
      }else{
        this.listQuery.start_time = undefined
        this.listQuery.end_time = undefined
      }
      
    },
    setUpdateRoom(data) {
      updateRoom(data).then(res => {
        if(res.code === 200) {
          this.$message({
            type: 'success',
            message: '房间号更改成功'
          })
          this.changeRoomVisible = false
          this.getList()
        }
      })
    },
    // 禁止输入中文
    check(str){ 
      let temp=""
      for(var i=0;i<str.length;i++) {
        if(str.charCodeAt(i)>0&&str.charCodeAt(i)<255) {
          temp+=str.charAt(i)
        }
      }
      return temp 
    },
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },
  }
}
</script>
